package com.vilen.basic.service;

import com.vilen.basic.model.WeixinMenu;
import com.vilen.weixin.dao.IWeixinMenuDao;
import com.vilen.weixin.model.WeixinMenuDto;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/2/14.
 */
@Service("weixinMenuService")
public class WeixinMenuService implements IWeixinMenuService{
    @Inject
    private IWeixinMenuDao weixinMenuDao;

    @Override
    public void add(WeixinMenu wm) {
        if(wm.getType().equals("click")) {
            wm.setMenuKey("KEY_" + System.currentTimeMillis());
        }
        weixinMenuDao.add(wm);
    }

    @Override
    public void delete(int id) {
        weixinMenuDao.delete(id);
    }

    @Override
    public void update(WeixinMenu wm) {
        //完成了key值的添加
        if(wm.getType().equals("click")) {
            wm.setMenuKey("KEY_" + System.currentTimeMillis());
        }
        weixinMenuDao.update(wm);
    }

    @Override
    public WeixinMenu load(int id) {
        return weixinMenuDao.load(id);
    }

    @Override
    public List<WeixinMenu> listAll() {
        return weixinMenuDao.listAll();
    }

    @Override
    public WeixinMenu loadByKey(String key) {
        return weixinMenuDao.loadByKey(key);
    }

    @Override
    public List<WeixinMenuDto> generateWeixinMenuDto() {
        List<WeixinMenu> menus = this.listAll();
        List<WeixinMenuDto> menuDtos = new ArrayList<WeixinMenuDto>();
        WeixinMenuDto wmd = null;
        for(WeixinMenu wm:menus) {
            wmd = new WeixinMenuDto();
            wmd.setKey(wm.getMenuKey());
            wmd.setName(wm.getName());
            wmd.setType(wm.getType());
            wmd.setUrl(wm.getUrl());
            wmd.setId(wm.getId());
            if(wm.getPid()==null||wm.getPid()==0) {
              if(wmd.getSub_button()==null){
                    wmd.setSub_button(new ArrayList<WeixinMenuDto>());
                }
                menuDtos.add(wmd);
            }
            //说明有父类  通过id进行查找
            else {
                WeixinMenuDto twmd = findById(wm.getPid(),menuDtos);
                if(twmd==null) {
                    //throw new RuntimeException("菜单的父类对象有问题");
                }
                twmd.getSub_button().add(wmd);
            }
        }
        return menuDtos;
    }
    private WeixinMenuDto findById(int id,List<WeixinMenuDto> wmds) {

        for(WeixinMenuDto wmd:wmds) {
            if(wmd.getId() == id) {
                return wmd;
            }
        }
        return null;
    }
}
